package admin

import (
	"encoding/base64"
	"fmt"
	"github.com/gin-gonic/gin"
	"go-vue-blog-sever/gla"
	"go-vue-blog-sever/models"
	"go-vue-blog-sever/utils"
	"sync"
	"time"
)

func UserLogin(c *gin.Context) {
	var ad models.AdminModel
	if err := c.ShouldBindJSON(&ad.UsersModel); err != nil {
		utils.ResponseBad(c, gla.BindError, nil)
		utils.LoggerInfo(gla.BindError, err.Error(), &ad)
		return
	}
	pwd, err := base64.StdEncoding.DecodeString(ad.Password)
	if err != nil {
		utils.ResponseBad(c, gla.UserLoginBad, nil)
		utils.LoggerInfo(gla.UserLoginBad, fmt.Sprintf("解密失败 err=%v", err), &ad)
		return
	}
	ad.Password = string(pwd)
	//fmt.Printf("debug %v", ad)
	var findAd models.AdminModel
	if err = utils.MysqlDB.Table("users").Where("username=?", ad.Username).First(&findAd).Error; err != nil {
		utils.ResponseBad(c, gla.UserLoginBad, nil)
		utils.LoggerInfo(gla.UserLoginBad, err.Error(), &ad)
		return
	}
	if !utils.ValidateMd5(ad.Password, findAd.Sign, findAd.Password) {
		utils.ResponseBad(c, gla.UserLoginBad, nil)
		utils.LoggerInfo(gla.UserLoginBad, "密码错误", &ad)
		return
	}
	token, err := utils.NewToken(findAd.ID, findAd.Username, findAd.Password)
	if err != nil {
		utils.ResponseBad(c, gla.UserLoginBad, nil)
		utils.LoggerInfo(gla.UserLoginBad, err.Error(), &ad)
		return
	}
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		utils.MysqlDB.Table("users").Where("username=?", findAd.Username).Update("login_at", time.Now())
	}()
	utils.ResponseSuccess(c, gla.UserLoginSuccess, gin.H{
		"token":    token,
		"nickname": findAd.NickName,
		"img":      findAd.ImagePath,
		"login_at": time.Now(),
	})
	wg.Wait()
}

func UserLogout(c *gin.Context) {
	utils.ResponseSuccess(c, "登出成功", nil)
}
